package com.telit.common.util;

import org.springframework.context.MessageSource;
import org.springframework.context.i18n.LocaleContextHolder;

import java.util.Locale;


/**
 * 国际化语言工具类
 *
 * @author yuezhuang
 * @date 2022-10-03
 */
public class LanguageUtils {

    private static MessageSource messageSource;

    private static MessageSource getMessageSource() {
        if (messageSource == null) {
            messageSource = SpringContextHolder.getBean(MessageSource.class);
        }
        return messageSource;
    }

    /**
     * 根据请求
     */
    public static String codeMessage(String code) {
        return codeMessage(code, new Object[]{});
    }

    public static String codeMessage(String code, Object... arg) {
        return getMessage("errors." + code, arg);
    }

    /**
     * @param code：对应文本配置的key.
     *
     * @return 对应地区的语言消息字符串
     */
    public static String getMessage(String code) {
        return getMessage(code, new Object[]{});
    }

    public static String getMessage(String code, String defaultMessage) {
        return getMessage(code, defaultMessage, new Object[]{});
    }

    public static String getMessage(String code, String defaultMessage, Locale locale) {
        return getMessage(code, defaultMessage, locale, new Object[]{});
    }

    public static String getMessage(String code, Locale locale) {
        return getMessage(code, "", locale, new Object[]{});
    }

    public static String getMessage(String code, Object... args) {
        return getMessage(code, "", args);
    }

    public static String getMessage(String code, Locale locale, Object... args) {
        return getMessage(code, "", locale, args);
    }

    public static String getMessage(String code, String defaultMessage, Object... args) {
        Locale locale = LocaleContextHolder.getLocale();
        return getMessage(code, defaultMessage, locale, args);
    }

    public static String getMessage(String code, String defaultMessage, Locale locale, Object... args) {
        return getMessageSource().getMessage(code, args, defaultMessage, locale);
    }

}
